<template>
  <div class="procure-entry">
    <!-- 搜索表单 -->
    <div class="search-wrap mt20">
      <SearchForm
        ref="searchFormRef"
        :list="[...formList]"
        colBtn
        @submit="search"
        @reset="reset"
        @daterangeChange="daterangeChange"
      ></SearchForm>
    </div>

    <!-- 今日/昨日/近7日/近30日等，创建订单按钮，关键词搜索 -->
    <div class="center-search-wrap">
      <div>
        <div class="left">
          <div class="date-filter">
            <el-radio-group v-model="postData.date" @change="changeDate">
              <el-radio-button label="今天" :value="0" />
              <el-radio-button label="昨天" :value="1" />
              <el-radio-button label="近7天" :value="7" />
              <el-radio-button label="近30天" :value="30" />
            </el-radio-group>
          </div>
        </div>
        <div class="right">
          <!-- {{ searchFormRef.value.form }} -->
          <el-button class="ml20" :loading="downloading" type="primary" plain @click="downloadExcel"> 导出 </el-button>
          <el-button class="ml20" type="primary" @click="$router.push({ path: '/procure/entry/add', query: {} })">
            新建入库单
          </el-button>
          <!-- <el-button class="ml10" type="primary" plain :icon="RefreshRight" @click="resetCenter">重置</el-button> -->
        </div>
      </div>
    </div>

    <!-- 表单数据 -->
    <el-table class="jzt-table" :data="list" stripe style="width: 100%">
      <el-table-column prop="inboundNo" show-overflow-tooltip label="入库编码" width="180" />
      <el-table-column prop="anotherName" show-overflow-tooltip label="往来单位" width="100" />
      <el-table-column prop="type" show-overflow-tooltip label="入库类型" width="100">
        <template #default="scope">
          <span>{{
            scope.row.type === 1
              ? "采购入库"
              : scope.row.type === 2
                ? "仓库调拨"
                : scope.row.type === 3
                  ? "销售退货"
                  : scope.row.type === 4
                    ? "其他入库"
                    : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="associateCustomer" show-overflow-tooltip label="关联客户" width="100" />
      <el-table-column prop="customerName" show-overflow-tooltip label="借调客户" width="180">
        <template #default="scope">
          <span>{{ scope.row.secondmentCustomer || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="associateCode" show-overflow-tooltip label="关联编码" width="100" />
      <el-table-column prop="warehouseName" show-overflow-tooltip label="入库仓库" />
      <el-table-column prop="plainInboundNum" show-overflow-tooltip label="预计入库量" width="180" />
      <el-table-column prop="factInboundNum" show-overflow-tooltip label="实际入库量" width="180" />
      <el-table-column prop="status" label="入库状态" width="120">
        <template #default="scope">
          <el-tag v-show="scope.row.status === 1" type="warning"> 待入库 </el-tag>
          <el-tag v-show="scope.row.status === 2" type="primary"> 部分入库 </el-tag>
          <el-tag v-show="scope.row.status === 3" type="success"> 已入库 </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="logisticsTrackNo" show-overflow-tooltip label="物流编码" width="180" />
      <el-table-column prop="inboundTime" show-overflow-tooltip label="入库时间" width="180" />
      <el-table-column prop="createBy" show-overflow-tooltip label="创建人" width="180" />
      <el-table-column prop="remark" label="备注" width="224">
        <template #default="scope">
          <RemarkEditor v-model="scope.row.remark" :isEdit="false" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" prop="action" label="操作" width="203">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="toPath({ path: '/procure/entry/list', query: { inboundId: scope.row.inboundId } })"
          >
            清单
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="
              toPath({ path: '/procure/entry/detail', query: { inboundId: scope.row.inboundId, status: scope.row.status } })
            "
          >
            详情
          </el-button>
          <!-- <el-button link type="primary" size="small">打印</el-button> -->
          <el-button
            v-show="scope.row.status === 1 || scope.row.status === 2"
            link
            type="primary"
            size="small"
            @click="toPath({ path: '/procure/entry/put', query: { inboundId: scope.row.inboundId, status: scope.row.status } })"
          >
            入库
          </el-button>
          <el-button
            v-show="scope.row.status === 2"
            link
            type="danger"
            size="small"
            @click="
              () => {
                optionInfo.isShow = true;
                optionInfo.inboundId = scope.row.inboundId;
              }
            "
            >异常</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pt20 pb20" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.sizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 异常数据弹窗 -->
    <error :optionInfo="optionInfo" @close="close" @submit="errorSubmit" />
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, nextTick, onMounted, onUpdated } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import error from "./components/error";
import moment from "moment";
import { ListPage } from "@/apis/procure/warehouse";
import { createUserList, getPageApi, download } from "@/apis/procure/entry";
import RemarkEditor from "@/components/RemarkEditor";
import { useRouter } from "vue-router";
const router = useRouter();

const searchFormRef = ref();
const formList = ref([
  {
    label: "物流编码",
    model: "logisticsTrackNo",
    type: "input",
    labelWidth: "70"
  },
  {
    label: "往来单位",
    model: "shopFactory",
    type: "input",
    labelWidth: "70"
  },
  {
    label: "创建人",
    model: "createId",
    type: "select",
    labelWidth: "70",
    props: { label: "createBy", value: "createId" }
  },
  {
    label: "入库状态",
    model: "status",
    type: "select",
    labelWidth: "70",
    data: [
      { label: "待入库", value: "1" },
      { label: "部分入库", value: "2" },
      { label: "已入库", value: "3" }
    ]
  },
  {
    label: "入仓库",
    model: "warehouseId",
    type: "select",
    labelWidth: "70",
    props: { label: "warehouseName", value: "warehouseId" }
  },
  {
    label: "入库类型",
    model: "type",
    type: "select",
    labelWidth: "70",
    data: [
      { label: "采购入库", value: "1" },
      { label: "仓库调拨", value: "2" },
      { label: "销售退货", value: "3" },
      { label: "其他入库", value: "4" }
    ]
  },
  {
    label: "入库异常",
    model: "exceptionType",
    type: "select",
    labelWidth: "70",
    data: [
      { label: "遗漏待补发", value: "1" },
      { label: "改版", value: "2" }
    ]
  },
  {
    label: "入库时间",
    model: "entryTime",
    type: "daterange",
    labelWidth: "70"
  },
  {
    label: "关联编码",
    model: "associateCodeType-associateCode",
    type: "select-input",
    labelWidth: "70",
    data: [
      {
        value: 1,
        label: "入库编码"
      },
      {
        value: 2,
        label: "关联编码"
      }
    ]
  },
  {
    label: "客户信息",
    model: "infoKey-associateCustomer",
    type: "select-input",
    labelWidth: "70",
    data: [
      {
        value: 0,
        label: "全部"
      },
      {
        value: 1,
        label: "姓名"
      },
      {
        value: 2,
        label: "电话"
      }
    ]
  },
  {
    label: "是否借调客户",
    model: "secondmentCustomer",
    type: "select",
    labelWidth: "70",
    data: [
      {
        value: 1,
        label: "是"
      },
      {
        value: 0,
        label: "否"
      }
    ]
  },
  {
    label: "借调客户搜索",
    model: "secondmentCustomerKeyword",
    type: "input",
    placeholder: "请输入借调客户姓名或电话号码搜索",
    labelWidth: "70"
  },
  {
    label: "备注",
    model: "remark",
    type: "input",
    labelWidth: "70"
  },
  {}
]);
const formData = ref({});
const postData = ref({ date: null });
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const optionInfo = ref({ isShow: false });

onMounted(async () => {
  getList();
  const res = await ListPage({ page: 1, size: 9999 });
  const res2 = await createUserList();
  formList.value.map(item => {
    if (item.model === "warehouseId") {
      item.data = res.data.records;
    } else if (item.model === "createId") {
      item.data = res2.data;
    }
  });
});

const toPath = obj => {
  //打开新页签
  const routeUrl = router.resolve(obj);
  window.open(routeUrl.href, "_blank");
};

const changeDate = val => {
  const { start, end } = getTimeRange(val);
  formData.value.startDate = start;
  formData.value.endDate = end;
  getList();
};

const getTimeRange = num => {
  if (num !== null) {
    let start = "";
    let end = "";
    if (num === 0) {
      start = moment().startOf("day").format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
      end = moment().endOf("day").format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
    } else if (num === 1) {
      start = moment().subtract(1, "day").startOf("day").format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
      end = moment().subtract(1, "day").endOf("day").format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
    } else {
      start = moment()
        .subtract(num - 1, "day")
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
      end = moment().format("YYYY-MM-DD HH:mm:ss"); // 带有时分秒
    }

    searchFormRef.value.setFormData("entryTime", [start, end]);
    return { start, end };
  }
};

// 关闭异常数据弹窗
const close = () => {
  optionInfo.value.isShow = false;
};
//异常处理成功的回调
const errorSubmit = () => {
  optionInfo.value.isShow = false;
  getList();
};

//查询入库单列表数据
const getList = () => {
  getPageApi({
    ...formData.value,
    page: pagination.value.page,
    size: pagination.value.size,
    startDate: postData.value.date ? getTimeRange(postData.value.date).start : formData.value.startDate,
    endDate: postData.value.date ? getTimeRange(postData.value.date).end : formData.value.endDate
  }).then(res => {
    if (res.code === 200) {
      list.value = res.data.records;
      pagination.value.total = res.data.total;
    }
  });
};

// 表单查询组件submit回调
const search = form => {
  // console.log("查询表单数据===", form);
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    _form.startDate = form?.entryTime ? form?.entryTime[0] : null;
    _form.endDate = form?.entryTime ? form?.entryTime[1] : null;
    delete _form?.entryTime;
    delete _form?.infoKey;
    formData.value = _form;
    // console.log("处理后的数据", formData.value);
  } else {
    formData.value = {};
  }
  nextTick(() => {
    getList();
  });
};
//清空查询表单
const reset = () => {
  search("");
  daterangeChange();
};

const daterangeChange = () => {
  postData.value = { date: null };
};

//清空中间的查询条件
const resetCenter = () => {
  postData.value = {};
};

const handleSizeChange = val => {
  pagination.value.size = val;
  getList();
};
const handleCurrentChange = val => {
  pagination.value.page = val;
  getList();
};

const entryTime = ref([]);
onUpdated(() => {
  entryTime.value = searchFormRef.value.getFormData()?.entryTime;
});
const downloading = ref(false);
// 导出
const downloadExcel = async () => {
  if (entryTime.value?.length > 0) {
    downloading.value = true;
    const res = await download({
      startDate: entryTime.value[0],
      endDate: entryTime.value[1]
    });
    downloading.value = false;
    let url = window.URL.createObjectURL(res);
    const a = document.createElement("a");
    a.href = url;
    a.download = entryTime.value[0] + "-" + entryTime.value[1] + "入库单.xlsx";
    a.click();
    URL.revokeObjectURL(url);
  } else {
    ElMessage.error("请选择入库时间范围后进行导出！");
  }
};
</script>

<style lang="scss" scoped>
.procure-entry {
  height: calc(100% - 20px);
  overflow-y: auto;
  padding: 0 20px 20px 20px;

  .search-wrap {
    padding: 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .center-search-wrap {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    :deep(.el-input-group__prepend) {
      padding: 0;
      box-shadow: none;
    }
    :deep(.el-input.el-input-group.el-input-group--append.el-input-group--prepend) {
      & > .el-input-group__prepend {
        border-radius: 4px 0 0 4px;
        border: 1px solid #dcdfe6;
        border-right: none;
        .el-input__wrapper {
          border-radius: 4px;
        }
        .el-cascader.el-tooltip__trigger.el-tooltip__trigger {
          border-radius: 4px 0 0 4px;
        }
      }
      & > .el-input__wrapper {
        border: 1px solid #dcdfe6;
      }
    }
    :deep(.el-input__wrapper) {
      box-shadow: none;
    }
    & > div {
      display: flex;
      justify-content: space-between;
      padding: 20px 0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
        background-color: white;
        color: #007dff;
      }
    }
  }
}
</style>
